import * as bip39 from 'bip39'
import { randomBytes } from 'react-native-randombytes';

if (typeof Buffer === 'undefined') global.Buffer = require('buffer').Buffer;

export class BIPSigner {

    generateMnemonic() {
        return bip39.generateMnemonic(128, randomBytes)
    }

    mnemonicToEntropy(mnemonic) {
        return bip39.mnemonicToEntropy(mnemonic)
    }

    entropyToMnemonic(entropy) {
        return bip39.entropyToMnemonic(entropy)
    }

    mnemonicToEntropy(mnemonic) {
        const usedList = BIPSigner.determineWordList(mnemonic)
        if (!usedList) {
            throw Error('non-compatible secret')
        }
        return bip39.mnemonicToEntropy(mnemonic, usedList)
    }

    mnemonicToSeedSync(mnemonic, passphrase) {
        return bip39.mnemonicToSeedSync(mnemonic, passphrase)
    }

    static prepareMnemonic(mnemonic) {
        return mnemonic.trim().toLowerCase()
    }

    validateMnemonic(mnemonic) {
        const preparedMnemonic = BIPSigner.prepareMnemonic(mnemonic)
        const wordList = BIPSigner.determineWordList(preparedMnemonic)
        return bip39.validateMnemonic(preparedMnemonic, wordList)
    }

    static determineWordList(mnemonic) {
        for (const list of BIPSigner.wordLists()) {
            if (bip39.validateMnemonic(BIPSigner.prepareMnemonic(mnemonic), list)) {
                return list
            }
        }
        return undefined
    }

    static wordLists() {
        return [
            bip39.wordlists.english
            /*
                  bip39.wordlists.chinese_simplified,
                  bip39.wordlists.chinese_traditional,
                  bip39.wordlists.french,
                  bip39.wordlists.italian,
                  bip39.wordlists.japanese,
                  bip39.wordlists.korean,
                  bip39.wordlists.spanish
                  */
        ]
    }

}
